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