]> git.sesse.net Git - casparcg/blob - core/producer/scene/scene_producer.cpp
Merge pull request #501 from dimitry-ishenko-casparcg/next
[casparcg] / core / producer / scene / scene_producer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Helge Norberg, helge.norberg@svt.se
20 */
21
22 #include "../../StdAfx.h"
23
24 #include <common/future.h>
25 #include <common/prec_timer.h>
26
27 #include <boost/algorithm/string/split.hpp>
28 #include <boost/algorithm/string.hpp>
29
30 #include "scene_producer.h"
31
32 #include "../../frame/draw_frame.h"
33 #include "../../interaction/interaction_aggregator.h"
34 #include "../text/text_producer.h"
35
36 namespace caspar { namespace core { namespace scene {
37
38 layer::layer(const std::wstring& name, const spl::shared_ptr<frame_producer>& producer)
39         : name(name), producer(producer)
40 {
41         crop.lower_right.x.bind(producer.get()->pixel_constraints().width);
42         crop.lower_right.y.bind(producer.get()->pixel_constraints().height);
43         perspective.upper_right.x.bind(producer.get()->pixel_constraints().width);
44         perspective.lower_right.x.bind(producer.get()->pixel_constraints().width);
45         perspective.lower_right.y.bind(producer.get()->pixel_constraints().height);
46         perspective.lower_left.y.bind(producer.get()->pixel_constraints().height);
47 }
48
49 adjustments::adjustments()
50         : opacity(1.0)
51 {
52 }
53
54 struct timeline
55 {
56         std::map<int64_t, keyframe> keyframes;
57
58         void on_frame(int64_t frame)
59         {
60                 auto before = --keyframes.upper_bound(frame);
61                 bool found_before = before != keyframes.end() && before->first < frame;
62                 auto after = keyframes.upper_bound(frame);
63                 bool found_after = after != keyframes.end() && after->first > frame;
64                 auto exact_frame = keyframes.find(frame);
65                 bool found_exact_frame = exact_frame != keyframes.end();
66
67                 if (found_exact_frame)
68                 {
69                         exact_frame->second.on_destination_frame();
70
71                         auto next_frame = ++exact_frame;
72
73                         if (next_frame != keyframes.end() && next_frame->second.on_start_animate)
74                                 next_frame->second.on_start_animate();
75                 }
76                 else if (found_after)
77                 {
78                         int64_t start_frame = 0;
79
80                         if (found_before)
81                         {
82                                 start_frame = before->first;
83                         }
84
85                         if (after->second.on_start_animate && frame == 0)
86                                 after->second.on_start_animate();
87                         else if (after->second.on_animate_to)
88                                 after->second.on_animate_to(start_frame, frame);
89                 }
90         }
91 };
92
93 mark_action get_mark_action(const std::wstring& name)
94 {
95         if (name == L"start")
96                 return mark_action::start;
97         else if (name == L"stop")
98                 return mark_action::stop;
99         else if (name == L"jump_to")
100                 return mark_action::jump_to;
101         else if (name == L"remove")
102                 return mark_action::remove;
103         else
104                 CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Invalid mark_action " + name));
105 }
106
107 struct marker
108 {
109         mark_action             action;
110         std::wstring    label_argument;
111
112         marker(mark_action action, const std::wstring& label_argument)
113                 : action(action)
114                 , label_argument(label_argument)
115         {
116         }
117 };
118
119 struct scene_producer::impl
120 {
121         std::wstring                                                                                    producer_name_;
122         constraints                                                                                             pixel_constraints_;
123         video_format_desc                                                                               format_desc_;
124         std::list<layer>                                                                                layers_;
125         interaction_aggregator                                                                  aggregator_;
126         binding<double>                                                                                 frame_number_;
127         binding<int64_t>                                                                                timeline_frame_number_;
128         binding<double>                                                                                 speed_;
129         mutable tbb::atomic<int64_t>                                                    m_x_;
130         mutable tbb::atomic<int64_t>                                                    m_y_;
131         binding<int64_t>                                                                                mouse_x_;
132         binding<int64_t>                                                                                mouse_y_;
133         double                                                                                                  frame_fraction_         = 0.0;
134         std::map<void*, timeline>                                                               timelines_;
135         std::map<std::wstring, std::shared_ptr<core::variable>> variables_;
136         std::vector<std::wstring>                                                               variable_names_;
137         std::multimap<int64_t, marker>                                                  markers_by_frame_;
138         monitor::subject                                                                                monitor_subject_;
139         bool                                                                                                    paused_                         = true;
140         bool                                                                                                    removed_                        = false;
141         bool                                                                                                    going_to_mark_          = false;
142
143         impl(std::wstring producer_name, int width, int height, const video_format_desc& format_desc)
144                 : producer_name_(std::move(producer_name))
145                 , pixel_constraints_(width, height)
146                 , format_desc_(format_desc)
147                 , aggregator_([=] (double x, double y) { return collission_detect(x, y); })
148         {
149                 auto speed_variable = std::make_shared<core::variable_impl<double>>(L"1.0", true, 1.0);
150                 store_variable(L"scene_speed", speed_variable);
151                 speed_ = speed_variable->value();
152
153                 auto frame_variable = std::make_shared<core::variable_impl<double>>(L"-1", true, -1);
154                 store_variable(L"frame", frame_variable);
155                 frame_number_ = frame_variable->value();
156
157                 auto timeline_frame_variable = std::make_shared<core::variable_impl<int64_t>>(L"-1", false, -1);
158                 store_variable(L"timeline_frame", timeline_frame_variable);
159                 timeline_frame_number_ = timeline_frame_variable->value();
160
161                 auto mouse_x_variable = std::make_shared<core::variable_impl<int64_t>>(L"0", false, 0);
162                 auto mouse_y_variable = std::make_shared<core::variable_impl<int64_t>>(L"0", false, 0);
163                 store_variable(L"mouse_x", mouse_x_variable);
164                 store_variable(L"mouse_y", mouse_y_variable);
165                 mouse_x_ = mouse_x_variable->value();
166                 mouse_y_ = mouse_y_variable->value();
167                 m_x_ = 0;
168                 m_y_ = 0;
169         }
170
171         layer& create_layer(
172                         const spl::shared_ptr<frame_producer>& producer, int x, int y, const std::wstring& name)
173         {
174                 layer layer(name, producer);
175
176                 layer.position.x.set(x);
177                 layer.position.y.set(y);
178
179                 layers_.push_back(layer);
180
181                 return layers_.back();
182         }
183
184         void reverse_layers() {
185                 layers_.reverse();
186         }
187
188         void store_keyframe(void* timeline_identity, const keyframe& k)
189         {
190                 timelines_[timeline_identity].keyframes.insert(std::make_pair(k.destination_frame, k));
191         }
192
193         void store_variable(
194                         const std::wstring& name, const std::shared_ptr<core::variable>& var)
195         {
196                 variables_.insert(std::make_pair(name, var));
197                 variable_names_.push_back(name);
198         }
199
200         void add_mark(int64_t frame, mark_action action, const std::wstring& label)
201         {
202                 markers_by_frame_.insert(std::make_pair(frame, marker(action, label)));
203         }
204
205         core::variable& get_variable(const std::wstring& name)
206         {
207                 auto found = variables_.find(name);
208
209                 if (found == variables_.end())
210                         CASPAR_THROW_EXCEPTION(user_error() << msg_info(name + L" not found in scene"));
211
212                 return *found->second;
213         }
214
215         const std::vector<std::wstring>& get_variables() const
216         {
217                 return variable_names_;
218         }
219
220         binding<int64_t> timeline_frame()
221         {
222                 return timeline_frame_number_;
223         }
224
225         frame_transform get_transform(const layer& layer) const
226         {
227                 frame_transform transform;
228
229                 auto& anchor            = transform.image_transform.anchor;
230                 auto& pos                       = transform.image_transform.fill_translation;
231                 auto& scale                     = transform.image_transform.fill_scale;
232                 auto& angle                     = transform.image_transform.angle;
233                 auto& crop                      = transform.image_transform.crop;
234                 auto& pers                      = transform.image_transform.perspective;
235
236                 anchor[0]       = layer.anchor.x.get()                                                                          / layer.producer.get()->pixel_constraints().width.get();
237                 anchor[1]       = layer.anchor.y.get()                                                                          / layer.producer.get()->pixel_constraints().height.get();
238                 pos[0]          = layer.position.x.get()                                                                        / pixel_constraints_.width.get();
239                 pos[1]          = layer.position.y.get()                                                                        / pixel_constraints_.height.get();
240                 scale[0]        = layer.producer.get()->pixel_constraints().width.get()         / pixel_constraints_.width.get();
241                 scale[1]        = layer.producer.get()->pixel_constraints().height.get()        / pixel_constraints_.height.get();
242                 crop.ul[0]      = layer.crop.upper_left.x.get()                                                         / layer.producer.get()->pixel_constraints().width.get();
243                 crop.ul[1]      = layer.crop.upper_left.y.get()                                                         / layer.producer.get()->pixel_constraints().height.get();
244                 crop.lr[0]      = layer.crop.lower_right.x.get()                                                        / layer.producer.get()->pixel_constraints().width.get();
245                 crop.lr[1]      = layer.crop.lower_right.y.get()                                                        / layer.producer.get()->pixel_constraints().height.get();
246                 pers.ul[0]      = layer.perspective.upper_left.x.get()                                          / layer.producer.get()->pixel_constraints().width.get();
247                 pers.ul[1]      = layer.perspective.upper_left.y.get()                                          / layer.producer.get()->pixel_constraints().height.get();
248                 pers.ur[0]      = layer.perspective.upper_right.x.get()                                         / layer.producer.get()->pixel_constraints().width.get();
249                 pers.ur[1]      = layer.perspective.upper_right.y.get()                                         / layer.producer.get()->pixel_constraints().height.get();
250                 pers.lr[0]      = layer.perspective.lower_right.x.get()                                         / layer.producer.get()->pixel_constraints().width.get();
251                 pers.lr[1]      = layer.perspective.lower_right.y.get()                                         / layer.producer.get()->pixel_constraints().height.get();
252                 pers.ll[0]      = layer.perspective.lower_left.x.get()                                          / layer.producer.get()->pixel_constraints().width.get();
253                 pers.ll[1]      = layer.perspective.lower_left.y.get()                                          / layer.producer.get()->pixel_constraints().height.get();
254
255                 static const double PI = 3.141592653589793;
256
257                 angle           = layer.rotation.get() * PI / 180.0;
258
259                 transform.image_transform.opacity                               = layer.adjustments.opacity.get();
260                 transform.image_transform.is_key                                = layer.is_key.get();
261                 transform.image_transform.use_mipmap                    = layer.use_mipmap.get();
262                 transform.image_transform.blend_mode                    = layer.blend_mode.get();
263                 transform.image_transform.chroma.enable                 = layer.chroma_key.enable.get();
264                 transform.image_transform.chroma.target_hue             = layer.chroma_key.target_hue.get();
265                 transform.image_transform.chroma.hue_width              = layer.chroma_key.hue_width.get();
266                 transform.image_transform.chroma.min_saturation = layer.chroma_key.min_saturation.get();
267                 transform.image_transform.chroma.min_brightness = layer.chroma_key.min_brightness.get();
268                 transform.image_transform.chroma.softness               = layer.chroma_key.softness.get();
269                 transform.image_transform.chroma.spill                  = layer.chroma_key.spill.get();
270                 transform.image_transform.chroma.spill_darken   = layer.chroma_key.spill_darken.get();
271
272                 // Mark as sublayer, so it will be composited separately by the mixer.
273                 transform.image_transform.layer_depth = 1;
274
275                 return transform;
276         }
277
278         boost::optional<std::pair<int64_t, marker>> find_first_stop_or_jump_or_remove(int64_t start_frame, int64_t end_frame)
279         {
280                 auto lower = markers_by_frame_.lower_bound(start_frame);
281                 auto upper = markers_by_frame_.upper_bound(end_frame);
282
283                 if (lower == markers_by_frame_.end())
284                         return boost::none;
285
286                 for (auto iter = lower; iter != upper; ++iter)
287                 {
288                         auto action = iter->second.action;
289
290                         if (action == mark_action::stop || action == mark_action::jump_to || action == mark_action::remove)
291                                 return std::make_pair(iter->first, iter->second);
292                 }
293
294                 return boost::none;
295         }
296
297         boost::optional<std::pair<int64_t, marker>> find_first_start(int64_t start_frame)
298         {
299                 auto lower = markers_by_frame_.lower_bound(start_frame);
300
301                 if (lower == markers_by_frame_.end())
302                         return boost::none;
303
304                 for (auto iter = lower; iter != markers_by_frame_.end(); ++iter)
305                 {
306                         auto action = iter->second.action;
307
308                         if (action == mark_action::start)
309                                 return std::make_pair(iter->first, iter->second);
310                 }
311
312                 return boost::none;
313         }
314
315         draw_frame render_frame()
316         {
317                 if (format_desc_.field_count == 1)
318                         return render_progressive_frame();
319                 else
320                 {
321                         prec_timer timer;
322                         timer.tick_millis(0);
323
324                         auto field1 = render_progressive_frame();
325
326                         timer.tick(0.5 / format_desc_.fps);
327
328                         auto field2 = render_progressive_frame();
329
330                         return draw_frame::interlace(field1, field2, format_desc_.field_mode);
331                 }
332         }
333
334         void advance()
335         {
336                 frame_fraction_ += speed_.get();
337
338                 if (std::abs(frame_fraction_) >= 1.0)
339                 {
340                         int64_t delta = static_cast<int64_t>(frame_fraction_);
341                         auto previous_frame = timeline_frame_number_.get();
342                         auto next_frame = timeline_frame_number_.get() + delta;
343                         auto marker = find_first_stop_or_jump_or_remove(previous_frame + 1, next_frame);
344
345                         if (marker && marker->second.action == mark_action::remove)
346                         {
347                                 remove();
348                         }
349                         if (marker && !going_to_mark_)
350                         {
351                                 if (marker->second.action == mark_action::stop)
352                                 {
353                                         timeline_frame_number_.set(marker->first);
354                                         frame_fraction_ = 0.0;
355                                         paused_ = true;
356                                 }
357                                 else if (marker->second.action == mark_action::jump_to)
358                                 {
359                                         go_to_marker(marker->second.label_argument, 0);
360                                 }
361                         }
362                         else
363                         {
364                                 timeline_frame_number_.set(next_frame);
365                                 frame_fraction_ -= delta;
366                         }
367
368                         going_to_mark_ = false;
369                 }
370         }
371
372         draw_frame render_progressive_frame()
373         {
374                 if (removed_)
375                         return draw_frame::empty();
376
377                 mouse_x_.set(m_x_);
378                 mouse_y_.set(m_y_);
379
380                 if (!paused_)
381                         advance();
382
383                 frame_number_.set(frame_number_.get() + speed_.get());
384
385                 for (auto& timeline : timelines_)
386                         timeline.second.on_frame(timeline_frame_number_.get());
387
388                 std::vector<draw_frame> frames;
389
390                 for (auto& layer : layers_)
391                 {
392                         if (layer.hidden.get())
393                                 continue;
394
395                         draw_frame frame(layer.producer.get()->receive());
396                         frame.transform() = get_transform(layer);
397                         frames.push_back(frame);
398                 }
399
400                 return draw_frame(frames);
401         }
402
403         void on_interaction(const interaction_event::ptr& event)
404         {
405                 aggregator_.translate_and_send(event);
406         }
407
408         bool collides(double x, double y) const
409         {
410                 m_x_ = static_cast<int64_t>(x * pixel_constraints_.width.get());
411                 m_y_ = static_cast<int64_t>(y * pixel_constraints_.height.get());
412
413                 return static_cast<bool>((collission_detect(x, y)));
414         }
415
416         boost::optional<interaction_target> collission_detect(double x, double y) const
417         {
418                 for (auto& layer : layers_ | boost::adaptors::reversed)
419                 {
420                         if (layer.hidden.get())
421                                 continue;
422
423                         auto transform = get_transform(layer);
424                         auto translated = translate(x, y, transform);
425
426                         if (translated.first >= 0.0
427                                 && translated.first <= 1.0
428                                 && translated.second >= 0.0
429                                 && translated.second <= 1.0
430                                 && layer.producer.get()->collides(translated.first, translated.second))
431                         {
432                                 return std::make_pair(transform, static_cast<interaction_sink*>(layer.producer.get().get()));
433                         }
434                 }
435
436                 return boost::optional<interaction_target>();
437         }
438
439         std::future<std::wstring> call(const std::vector<std::wstring>& params)
440         {
441                 if (!params.empty() && boost::ends_with(params.at(0), L"()"))
442                         return make_ready_future(handle_call(params));
443                 else
444                         return make_ready_future(handle_variable_set(params));
445         }
446
447         std::wstring handle_variable_set(const std::vector<std::wstring>& params)
448         {
449                 for (int i = 0; i + 1 < params.size(); i += 2)
450                 {
451                         auto found = variables_.find(boost::to_lower_copy(params.at(i)));
452
453                         if (found != variables_.end() && found->second->is_public())
454                                 found->second->from_string(params.at(i + 1));
455                 }
456
457                 return L"";
458         }
459
460         std::wstring handle_call(const std::vector<std::wstring>& params)
461         {
462                 auto call = params.at(0);
463
464                 if (call == L"play()")
465                         go_to_marker(params.at(1), -1);
466                 else if (call == L"remove()")
467                         remove();
468                 else if (call == L"next()")
469                         next();
470                 else
471                         CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Unknown call " + call));
472
473                 return L"";
474         }
475
476         void remove()
477         {
478                 removed_ = true;
479                 layers_.clear();
480         }
481
482         void next()
483         {
484                 auto marker = find_first_start(timeline_frame_number_.get() + 1);
485
486                 if (marker)
487                 {
488                         timeline_frame_number_.set(marker->first - 1);
489                         frame_fraction_ = 0.0;
490                         paused_ = false;
491                         going_to_mark_ = true;
492                 }
493                 else
494                 {
495                         remove();
496                 }
497         }
498
499         void go_to_marker(const std::wstring& marker_name, int64_t offset)
500         {
501                 for (auto& marker : markers_by_frame_)
502                 {
503                         if (marker.second.label_argument == marker_name && marker.second.action == mark_action::start)
504                         {
505                                 timeline_frame_number_.set(marker.first + offset);
506                                 frame_fraction_ = 0.0;
507                                 paused_ = false;
508                                 going_to_mark_ = true;
509
510                                 return;
511                         }
512                 }
513
514                 if (marker_name == L"intro")
515                 {
516                         timeline_frame_number_.set(offset);
517                         frame_fraction_ = 0.0;
518                         paused_ = false;
519                         going_to_mark_ = true;
520                 }
521                 else if (marker_name == L"outro")
522                 {
523                         remove();
524                 }
525                 else
526                         CASPAR_LOG(info) << print() << L" no marker called " << marker_name << " found";
527         }
528
529         std::wstring print() const
530         {
531                 return L"scene[type=" + name() + L"]";
532         }
533
534         std::wstring name() const
535         {
536                 return producer_name_;
537         }
538
539         boost::property_tree::wptree info() const
540         {
541                 boost::property_tree::wptree info;
542                 info.add(L"type", L"scene");
543                 info.add(L"producer-name", name());
544                 info.add(L"frame-number", frame_number_.get());
545                 info.add(L"timeline-frame-number", timeline_frame_number_.get());
546
547                 for (auto& var : variables_)
548                 {
549                         boost::property_tree::wptree variable_info;
550
551                         variable_info.add(L"name", var.first);
552                         variable_info.add(L"public", var.second->is_public());
553                         variable_info.add(L"value", var.second->to_string());
554
555                         info.add_child(L"variables.variable", variable_info);
556                 }
557
558                 for (auto& layer : layers_)
559                 {
560                         boost::property_tree::wptree layer_info;
561
562                         layer_info.add(L"name", layer.name.get());
563                         layer_info.add_child(L"producer", layer.producer.get()->info());
564                         layer_info.add(L"x", layer.position.x.get());
565                         layer_info.add(L"y", layer.position.y.get());
566                         layer_info.add(L"width", layer.producer.get()->pixel_constraints().width.get());
567                         layer_info.add(L"height", layer.producer.get()->pixel_constraints().height.get());
568
569                         info.add_child(L"layers.layer", layer_info);
570                 }
571
572                 return info;
573         }
574
575         monitor::subject& monitor_output()
576         {
577                 return monitor_subject_;
578         }
579 };
580
581 scene_producer::scene_producer(std::wstring producer_name, int width, int height, const video_format_desc& format_desc)
582         : impl_(new impl(std::move(producer_name), width, height, format_desc))
583 {
584 }
585
586 scene_producer::~scene_producer()
587 {
588 }
589
590 layer& scene_producer::create_layer(
591                 const spl::shared_ptr<frame_producer>& producer, int x, int y, const std::wstring& name)
592 {
593         return impl_->create_layer(producer, x, y, name);
594 }
595
596 layer& scene_producer::create_layer(
597                 const spl::shared_ptr<frame_producer>& producer, const std::wstring& name)
598 {
599         return impl_->create_layer(producer, 0, 0, name);
600 }
601
602 void scene_producer::reverse_layers() {
603         impl_->reverse_layers();
604 }
605
606 binding<int64_t> scene_producer::timeline_frame()
607 {
608         return impl_->timeline_frame();
609 }
610
611 draw_frame scene_producer::receive_impl()
612 {
613         return impl_->render_frame();
614 }
615
616 constraints& scene_producer::pixel_constraints() { return impl_->pixel_constraints_; }
617
618 void scene_producer::on_interaction(const interaction_event::ptr& event)
619 {
620         impl_->on_interaction(event);
621 }
622
623 bool scene_producer::collides(double x, double y) const
624 {
625         return impl_->collides(x, y);
626 }
627
628 std::wstring scene_producer::print() const
629 {
630         return impl_->print();
631 }
632
633 std::wstring scene_producer::name() const
634 {
635         return impl_->name();
636 }
637
638 boost::property_tree::wptree scene_producer::info() const
639 {
640         return impl_->info();
641 }
642
643 std::future<std::wstring> scene_producer::call(const std::vector<std::wstring>& params)
644 {
645         return impl_->call(params);
646 }
647
648 monitor::subject& scene_producer::monitor_output()
649 {
650         return impl_->monitor_output();
651 }
652
653 void scene_producer::store_keyframe(void* timeline_identity, const keyframe& k)
654 {
655         impl_->store_keyframe(timeline_identity, k);
656 }
657
658 void scene_producer::store_variable(
659                 const std::wstring& name, const std::shared_ptr<core::variable>& var)
660 {
661         impl_->store_variable(name, var);
662 }
663
664 void scene_producer::add_mark(int64_t frame, mark_action action, const std::wstring& label)
665 {
666         impl_->add_mark(frame, action, label);
667 }
668
669 core::variable& scene_producer::get_variable(const std::wstring& name)
670 {
671         return impl_->get_variable(name);
672 }
673
674 const std::vector<std::wstring>& scene_producer::get_variables() const
675 {
676         return impl_->get_variables();
677 }
678
679 }}}