Supporters update.
[dcpomatic.git] / src / lib / playlist.cc
1 /*
2     Copyright (C) 2013-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic 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 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic 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 DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "audio_content.h"
23 #include "compose.hpp"
24 #include "config.h"
25 #include "content_factory.h"
26 #include "dcp_content.h"
27 #include "digester.h"
28 #include "ffmpeg_content.h"
29 #include "ffmpeg_decoder.h"
30 #include "image_decoder.h"
31 #include "job.h"
32 #include "playlist.h"
33 #include "text_content.h"
34 #include "util.h"
35 #include "video_content.h"
36 #include <libcxml/cxml.h>
37 #include <libxml++/libxml++.h>
38 #include <boost/bind/placeholders.hpp>
39 #include <iostream>
40
41 #include "i18n.h"
42
43
44 using std::cout;
45 using std::dynamic_pointer_cast;
46 using std::list;
47 using std::max;
48 using std::min;
49 using std::pair;
50 using std::shared_ptr;
51 using std::string;
52 using std::vector;
53 using std::weak_ptr;
54 using boost::optional;
55 using namespace dcpomatic;
56 #if BOOST_VERSION >= 106100
57 using namespace boost::placeholders;
58 #endif
59
60
61 class ContentSorter
62 {
63 public:
64         bool operator()(shared_ptr<Content> a, shared_ptr<Content> b)
65         {
66                 if (a->position() != b->position()) {
67                         return a->position() < b->position();
68                 }
69
70                 /* Put video before audio if they start at the same time */
71                 if (a->video && !b->video) {
72                         return true;
73                 } else if (!a->video && b->video) {
74                         return false;
75                 }
76
77                 /* Last resort */
78                 return a->digest() < b->digest();
79         }
80 };
81
82
83 Playlist::~Playlist ()
84 {
85         boost::mutex::scoped_lock lm (_mutex);
86         _content.clear ();
87         disconnect ();
88 }
89
90
91 void
92 Playlist::content_change (weak_ptr<const Film> weak_film, ChangeType type, weak_ptr<Content> content, int property, bool frequent)
93 {
94         auto film = weak_film.lock ();
95         DCPOMATIC_ASSERT (film);
96
97         if (type == ChangeType::DONE) {
98                 if (
99                         property == ContentProperty::TRIM_START ||
100                         property == ContentProperty::TRIM_END ||
101                         property == ContentProperty::LENGTH ||
102                         property == VideoContentProperty::FRAME_TYPE
103                         ) {
104                         /* Don't respond to position changes here, as:
105                            - sequencing after earlier/later changes is handled by move_earlier/move_later
106                            - any other position changes will be timeline drags which should not result in content
107                            being sequenced.
108                         */
109                         maybe_sequence (film);
110                 }
111
112                 if (
113                         property == ContentProperty::POSITION ||
114                         property == ContentProperty::LENGTH ||
115                         property == ContentProperty::TRIM_START ||
116                         property == ContentProperty::TRIM_END) {
117
118                         bool changed = false;
119
120                         {
121                                 boost::mutex::scoped_lock lm (_mutex);
122                                 ContentList old = _content;
123                                 sort (_content.begin(), _content.end(), ContentSorter ());
124                                 changed = _content != old;
125                         }
126
127                         if (changed) {
128                                 OrderChange ();
129                         }
130
131                         /* The length might have changed, and that's good enough for this signal */
132                         LengthChange ();
133                 }
134         }
135
136         ContentChange (type, content, property, frequent);
137 }
138
139
140 void
141 Playlist::maybe_sequence (shared_ptr<const Film> film)
142 {
143         if (!_sequence || _sequencing) {
144                 return;
145         }
146
147         _sequencing = true;
148
149         auto cont = content ();
150
151         /* Keep track of the content that we've set the position of so that we don't
152            do it twice.
153         */
154         ContentList placed;
155
156         /* Video */
157
158         DCPTime next_left;
159         DCPTime next_right;
160         for (auto i: cont) {
161                 if (!i->video) {
162                         continue;
163                 }
164
165                 if (i->video->frame_type() == VideoFrameType::THREE_D_RIGHT) {
166                         i->set_position (film, next_right);
167                         next_right = i->end(film);
168                 } else {
169                         i->set_position (film, next_left);
170                         next_left = i->end(film);
171                 }
172
173                 placed.push_back (i);
174         }
175
176         /* Captions */
177
178         DCPTime next;
179         for (auto i: cont) {
180                 if (i->text.empty() || find (placed.begin(), placed.end(), i) != placed.end()) {
181                         continue;
182                 }
183
184                 i->set_position (film, next);
185                 next = i->end(film);
186         }
187
188
189         /* This won't change order, so it does not need a sort */
190
191         _sequencing = false;
192 }
193
194
195 string
196 Playlist::video_identifier () const
197 {
198         string t;
199
200         for (auto i: content()) {
201                 bool burn = false;
202                 for (auto j: i->text) {
203                         if (j->burn()) {
204                                 burn = true;
205                         }
206                 }
207                 if (i->video || burn) {
208                         t += i->identifier ();
209                 }
210         }
211
212         Digester digester;
213         digester.add (t.c_str(), t.length());
214         return digester.get ();
215 }
216
217
218 /** @param film Film that this Playlist is for.
219  *  @param node &lt;Playlist&gt; node.
220  *  @param version Metadata version number.
221  *  @param notes Output notes about that happened.
222  */
223 void
224 Playlist::set_from_xml (shared_ptr<const Film> film, cxml::ConstNodePtr node, int version, list<string>& notes)
225 {
226         boost::mutex::scoped_lock lm (_mutex);
227
228         for (auto i: node->node_children ("Content")) {
229                 auto content = content_factory (i, version, notes);
230
231                 /* See if this content should be nudged to start on a video frame */
232                 auto const old_pos = content->position();
233                 content->set_position(film, old_pos);
234                 if (old_pos != content->position()) {
235                         string note = _("Your project contains video content that was not aligned to a frame boundary.");
236                         note += "  ";
237                         if (old_pos < content->position()) {
238                                 note += String::compose(
239                                         _("The file %1 has been moved %2 milliseconds later."),
240                                         content->path_summary(), DCPTime(content->position() - old_pos).seconds() * 1000
241                                         );
242                         } else {
243                                 note += String::compose(
244                                         _("The file %1 has been moved %2 milliseconds earlier."),
245                                         content->path_summary(), DCPTime(content->position() - old_pos).seconds() * 1000
246                                         );
247                         }
248                         notes.push_back (note);
249                 }
250
251                 /* ...or have a start trim which is an integer number of frames */
252                 auto const old_trim = content->trim_start();
253                 content->set_trim_start(film, old_trim);
254                 if (old_trim != content->trim_start()) {
255                         string note = _("Your project contains video content whose trim was not aligned to a frame boundary.");
256                         note += "  ";
257                         if (old_trim < content->trim_start()) {
258                                 note += String::compose(
259                                         _("The file %1 has been trimmed by %2 milliseconds more."),
260                                         content->path_summary(), ContentTime(content->trim_start() - old_trim).seconds() * 1000
261                                         );
262                         } else {
263                                 note += String::compose(
264                                         _("The file %1 has been trimmed by %2 milliseconds less."),
265                                         content->path_summary(), ContentTime(old_trim - content->trim_start()).seconds() * 1000
266                                         );
267                         }
268                         notes.push_back (note);
269                 }
270
271                 _content.push_back (content);
272         }
273
274         /* This shouldn't be necessary but better safe than sorry (there could be old files) */
275         sort (_content.begin(), _content.end(), ContentSorter ());
276
277         reconnect (film);
278 }
279
280
281 /** @param node &lt;Playlist&gt; node.
282  *  @param with_content_paths true to include &lt;Path&gt; nodes in &lt;Content&gt; nodes, false to omit them.
283  */
284 void
285 Playlist::as_xml (xmlpp::Node* node, bool with_content_paths)
286 {
287         for (auto i: content()) {
288                 i->as_xml (node->add_child ("Content"), with_content_paths);
289         }
290 }
291
292
293 void
294 Playlist::add (shared_ptr<const Film> film, shared_ptr<Content> c)
295 {
296         Change (ChangeType::PENDING);
297
298         {
299                 boost::mutex::scoped_lock lm (_mutex);
300                 _content.push_back (c);
301                 sort (_content.begin(), _content.end(), ContentSorter ());
302                 reconnect (film);
303         }
304
305         Change (ChangeType::DONE);
306
307         LengthChange ();
308 }
309
310
311 void
312 Playlist::remove (shared_ptr<Content> c)
313 {
314         Change (ChangeType::PENDING);
315
316         bool cancelled = false;
317
318         {
319                 boost::mutex::scoped_lock lm (_mutex);
320
321                 auto i = _content.begin ();
322                 while (i != _content.end() && *i != c) {
323                         ++i;
324                 }
325
326                 if (i != _content.end()) {
327                         _content.erase (i);
328                 } else {
329                         cancelled = true;
330                 }
331         }
332
333         if (cancelled) {
334                 Change (ChangeType::CANCELLED);
335         } else {
336                 Change (ChangeType::DONE);
337         }
338
339         /* This won't change order, so it does not need a sort */
340
341         LengthChange ();
342 }
343
344
345 void
346 Playlist::remove (ContentList c)
347 {
348         Change (ChangeType::PENDING);
349
350         {
351                 boost::mutex::scoped_lock lm (_mutex);
352
353                 for (auto i: c) {
354                         auto j = _content.begin ();
355                         while (j != _content.end() && *j != i) {
356                                 ++j;
357                         }
358
359                         if (j != _content.end ()) {
360                                 _content.erase (j);
361                         }
362                 }
363         }
364
365         Change (ChangeType::DONE);
366
367         /* This won't change order, so it does not need a sort */
368
369         LengthChange ();
370 }
371
372
373 class FrameRateCandidate
374 {
375 public:
376         FrameRateCandidate (float source_, int dcp_)
377                 : source (source_)
378                 , dcp (dcp_)
379         {}
380
381         float source;
382         int dcp;
383 };
384
385
386 /** @return the best frame rate from Config::_allowed_dcp_frame_rates for the content in this list */
387 int
388 Playlist::best_video_frame_rate () const
389 {
390         auto const allowed_dcp_frame_rates = Config::instance()->allowed_dcp_frame_rates ();
391
392         /* Work out what rates we could manage, including those achieved by using skip / repeat */
393         list<FrameRateCandidate> candidates;
394
395         /* Start with the ones without skip / repeat so they will get matched in preference to skipped/repeated ones */
396         for (auto i: allowed_dcp_frame_rates) {
397                 candidates.push_back (FrameRateCandidate(i, i));
398         }
399
400         /* Then the skip/repeat ones */
401         for (auto i: allowed_dcp_frame_rates) {
402                 candidates.push_back (FrameRateCandidate (float(i) / 2, i));
403                 candidates.push_back (FrameRateCandidate (float(i) * 2, i));
404         }
405
406         /* Pick the best one */
407         float error = std::numeric_limits<float>::max ();
408         optional<FrameRateCandidate> best;
409         auto i = candidates.begin();
410         while (i != candidates.end()) {
411
412                 float this_error = 0;
413                 for (auto j: content()) {
414                         if (!j->video || !j->video_frame_rate()) {
415                                 continue;
416                         }
417
418                         /* Best error for this content; we could use the content as-is or double its rate */
419                         float best_error = min (
420                                 float (fabs (i->source - j->video_frame_rate().get())),
421                                 float (fabs (i->source - j->video_frame_rate().get() * 2))
422                                 );
423
424                         /* Use the largest difference between DCP and source as the "error" */
425                         this_error = max (this_error, best_error);
426                 }
427
428                 if (this_error < error) {
429                         error = this_error;
430                         best = *i;
431                 }
432
433                 ++i;
434         }
435
436         if (!best) {
437                 return 24;
438         }
439
440         return best->dcp;
441 }
442
443
444 /** @return length of the playlist from time 0 to the last thing on the playlist */
445 DCPTime
446 Playlist::length (shared_ptr<const Film> film) const
447 {
448         DCPTime len;
449         for (auto i: content()) {
450                 len = max (len, i->end(film));
451         }
452
453         return len;
454 }
455
456
457 /** @return position of the first thing on the playlist, if it's not empty */
458 optional<DCPTime>
459 Playlist::start () const
460 {
461         auto cont = content ();
462         if (cont.empty()) {
463                 return {};
464         }
465
466         auto start = DCPTime::max ();
467         for (auto i: cont) {
468                 start = min (start, i->position ());
469         }
470
471         return start;
472 }
473
474
475 /** Must be called with a lock held on _mutex */
476 void
477 Playlist::disconnect ()
478 {
479         for (auto& i: _content_connections) {
480                 i.disconnect ();
481         }
482
483         _content_connections.clear ();
484 }
485
486
487 /** Must be called with a lock held on _mutex */
488 void
489 Playlist::reconnect (shared_ptr<const Film> film)
490 {
491         disconnect ();
492
493         for (auto i: _content) {
494                 _content_connections.push_back (i->Change.connect(boost::bind(&Playlist::content_change, this, film, _1, _2, _3, _4)));
495         }
496 }
497
498
499 DCPTime
500 Playlist::video_end (shared_ptr<const Film> film) const
501 {
502         DCPTime end;
503         for (auto i: content()) {
504                 if (i->video) {
505                         end = max (end, i->end(film));
506                 }
507         }
508
509         return end;
510 }
511
512
513 DCPTime
514 Playlist::text_end (shared_ptr<const Film> film) const
515 {
516         DCPTime end;
517         for (auto i: content()) {
518                 if (!i->text.empty ()) {
519                         end = max (end, i->end(film));
520                 }
521         }
522
523         return end;
524 }
525
526
527 FrameRateChange
528 Playlist::active_frame_rate_change (DCPTime t, int dcp_video_frame_rate) const
529 {
530         auto cont = content ();
531         for (ContentList::const_reverse_iterator i = cont.rbegin(); i != cont.rend(); ++i) {
532                 if (!(*i)->video) {
533                         continue;
534                 }
535
536                 if ((*i)->position() <= t) {
537                         /* This is the first piece of content (going backwards...) that starts before t,
538                            so it's the active one.
539                         */
540                         if ((*i)->video_frame_rate ()) {
541                                 /* This content specified a rate, so use it */
542                                 return FrameRateChange ((*i)->video_frame_rate().get(), dcp_video_frame_rate);
543                         } else {
544                                 /* No specified rate so just use the DCP one */
545                                 return FrameRateChange (dcp_video_frame_rate, dcp_video_frame_rate);
546                         }
547                 }
548         }
549
550         return FrameRateChange (dcp_video_frame_rate, dcp_video_frame_rate);
551 }
552
553
554 void
555 Playlist::set_sequence (bool s)
556 {
557         _sequence = s;
558 }
559
560
561 /** @return content in ascending order of position */
562 ContentList
563 Playlist::content () const
564 {
565         boost::mutex::scoped_lock lm (_mutex);
566         return _content;
567 }
568
569
570 void
571 Playlist::repeat (shared_ptr<const Film> film, ContentList c, int n)
572 {
573         pair<DCPTime, DCPTime> range (DCPTime::max(), DCPTime());
574         for (auto i: c) {
575                 range.first = min (range.first, i->position ());
576                 range.second = max (range.second, i->position ());
577                 range.first = min (range.first, i->end(film));
578                 range.second = max (range.second, i->end(film));
579         }
580
581         Change (ChangeType::PENDING);
582
583         {
584                 boost::mutex::scoped_lock lm (_mutex);
585
586                 DCPTime pos = range.second;
587                 for (int i = 0; i < n; ++i) {
588                         for (auto j: c) {
589                                 auto copy = j->clone ();
590                                 copy->set_position (film, pos + copy->position() - range.first);
591                                 _content.push_back (copy);
592                         }
593                         pos += range.second - range.first;
594                 }
595
596                 sort (_content.begin(), _content.end(), ContentSorter ());
597                 reconnect (film);
598         }
599
600         Change (ChangeType::DONE);
601 }
602
603
604 void
605 Playlist::move_earlier (shared_ptr<const Film> film, shared_ptr<Content> c)
606 {
607         auto cont = content ();
608         auto previous = cont.end();
609         auto i = cont.begin();
610         while (i != cont.end() && *i != c) {
611                 previous = i;
612                 ++i;
613         }
614
615         DCPOMATIC_ASSERT (i != cont.end());
616         if (previous == cont.end()) {
617                 return;
618         }
619
620         auto previous_c = *previous;
621
622         auto const p = previous_c->position ();
623         previous_c->set_position (film, p + c->length_after_trim(film));
624         c->set_position (film, p);
625 }
626
627
628 void
629 Playlist::move_later (shared_ptr<const Film> film, shared_ptr<Content> c)
630 {
631         auto cont = content ();
632
633         auto iter = std::find(cont.begin(), cont.end(), c);
634         DCPOMATIC_ASSERT(iter != cont.end());
635
636         ContentList::iterator next = std::next(iter);
637         if (next == cont.end()) {
638                 /* This content is already at the end */
639                 return;
640         }
641
642         (*next)->set_position(film, c->position());
643         c->set_position(film, c->position() + (*next)->length_after_trim(film));
644 }
645
646
647 int64_t
648 Playlist::required_disk_space (shared_ptr<const Film> film, int j2k_bandwidth, int audio_channels, int audio_frame_rate) const
649 {
650         int64_t video = uint64_t(j2k_bandwidth / 8) * length(film).seconds();
651         int64_t audio = uint64_t(audio_channels) * audio_frame_rate * 3 * length(film).seconds();
652
653         for (auto i: content()) {
654                 auto d = dynamic_pointer_cast<DCPContent> (i);
655                 if (d) {
656                         if (d->reference_video()) {
657                                 video -= uint64_t (j2k_bandwidth / 8) * d->length_after_trim(film).seconds();
658                         }
659                         if (d->reference_audio()) {
660                                 audio -= uint64_t(audio_channels) * audio_frame_rate * 3 * d->length_after_trim(film).seconds();
661                         }
662                 }
663         }
664
665         /* Add on 64k for bits and pieces (metadata, subs etc) */
666         return video + audio + 65536;
667 }
668
669
670 string
671 Playlist::content_summary (shared_ptr<const Film> film, DCPTimePeriod period) const
672 {
673         string best_summary;
674         int best_score = -1;
675         for (auto i: content()) {
676                 int score = 0;
677                 auto const o = i->period(film).overlap(period);
678                 if (o) {
679                         score += 100 * o.get().duration().get() / period.duration().get();
680                 }
681
682                 if (i->video) {
683                         score += 100;
684                 }
685
686                 if (score > best_score) {
687                         best_summary = i->path(0).filename().string();
688                         best_score = score;
689                 }
690         }
691
692         return best_summary;
693 }
694
695
696 pair<double, double>
697 Playlist::speed_up_range (int dcp_video_frame_rate) const
698 {
699         pair<double, double> range (DBL_MAX, -DBL_MAX);
700
701         for (auto i: content()) {
702                 if (!i->video) {
703                         continue;
704                 }
705                 if (i->video_frame_rate()) {
706                         FrameRateChange const frc (i->video_frame_rate().get(), dcp_video_frame_rate);
707                         range.first = min (range.first, frc.speed_up);
708                         range.second = max (range.second, frc.speed_up);
709                 } else {
710                         FrameRateChange const frc (dcp_video_frame_rate, dcp_video_frame_rate);
711                         range.first = min (range.first, frc.speed_up);
712                         range.second = max (range.second, frc.speed_up);
713                 }
714         }
715
716         return range;
717 }