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