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