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