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