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