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