More fixes for errors / crashes / misbehaviour with content changes
[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_may_change ()
69 {
70         ContentMayChange ();
71 }
72
73 void
74 Playlist::content_not_changed ()
75 {
76         ContentNotChanged ();
77 }
78
79 void
80 Playlist::content_changed (weak_ptr<Content> content, int property, bool frequent)
81 {
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 ();
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         ContentChanged (content, property, frequent);
110 }
111
112 void
113 Playlist::maybe_sequence ()
114 {
115         if (!_sequence || _sequencing) {
116                 return;
117         }
118
119         _sequencing = true;
120
121         /* Keep track of the content that we've set the position of so that we don't
122            do it twice.
123         */
124         ContentList placed;
125
126         /* Video */
127
128         DCPTime next_left;
129         DCPTime next_right;
130         BOOST_FOREACH (shared_ptr<Content> i, _content) {
131                 if (!i->video) {
132                         continue;
133                 }
134
135                 if (i->video->frame_type() == VIDEO_FRAME_TYPE_3D_RIGHT) {
136                         i->set_position (next_right);
137                         next_right = i->end();
138                 } else {
139                         i->set_position (next_left);
140                         next_left = i->end();
141                 }
142
143                 placed.push_back (i);
144         }
145
146         /* Captions */
147
148         DCPTime next;
149         BOOST_FOREACH (shared_ptr<Content> i, _content) {
150                 if (i->text.empty() || find (placed.begin(), placed.end(), i) != placed.end()) {
151                         continue;
152                 }
153
154                 i->set_position (next);
155                 next = i->end();
156         }
157
158
159         /* This won't change order, so it does not need a sort */
160
161         _sequencing = false;
162 }
163
164 string
165 Playlist::video_identifier () const
166 {
167         string t;
168
169         BOOST_FOREACH (shared_ptr<const Content> i, _content) {
170                 bool burn = false;
171                 BOOST_FOREACH (shared_ptr<TextContent> j, i->text) {
172                         if (j->burn()) {
173                                 burn = true;
174                         }
175                 }
176                 if (i->video || burn) {
177                         t += i->identifier ();
178                 }
179         }
180
181         Digester digester;
182         digester.add (t.c_str(), t.length());
183         return digester.get ();
184 }
185
186 /** @param film Film that this Playlist is for.
187  *  @param node &lt;Playlist&gt; node.
188  *  @param version Metadata version number.
189  *  @param notes Output notes about that happened.
190  */
191 void
192 Playlist::set_from_xml (shared_ptr<const Film> film, cxml::ConstNodePtr node, int version, list<string>& notes)
193 {
194         BOOST_FOREACH (cxml::NodePtr i, node->node_children ("Content")) {
195                 _content.push_back (content_factory (film, i, version, notes));
196         }
197
198         /* This shouldn't be necessary but better safe than sorry (there could be old files) */
199         sort (_content.begin(), _content.end(), ContentSorter ());
200
201         reconnect ();
202 }
203
204 /** @param node &lt;Playlist&gt; node.
205  *  @param with_content_paths true to include &lt;Path&gt; nodes in &lt;Content&gt; nodes, false to omit them.
206  */
207 void
208 Playlist::as_xml (xmlpp::Node* node, bool with_content_paths)
209 {
210         BOOST_FOREACH (shared_ptr<Content> i, _content) {
211                 i->as_xml (node->add_child ("Content"), with_content_paths);
212         }
213 }
214
215 void
216 Playlist::add (shared_ptr<Content> c)
217 {
218         _content.push_back (c);
219         sort (_content.begin(), _content.end(), ContentSorter ());
220         reconnect ();
221         Changed ();
222 }
223
224 void
225 Playlist::remove (shared_ptr<Content> c)
226 {
227         ContentList::iterator i = _content.begin ();
228         while (i != _content.end() && *i != c) {
229                 ++i;
230         }
231
232         if (i != _content.end ()) {
233                 _content.erase (i);
234                 Changed ();
235         }
236
237         /* This won't change order, so it does not need a sort */
238 }
239
240 void
241 Playlist::remove (ContentList c)
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         Changed ();
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 () const
330 {
331         DCPTime len;
332         BOOST_FOREACH (shared_ptr<const Content> i, _content) {
333                 len = max (len, i->end());
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::reconnect ()
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         BOOST_FOREACH (shared_ptr<Content> i, _content) {
365                 _content_connections.push_back (i->MayChange.connect(boost::bind(&Playlist::content_may_change, this)));
366                 _content_connections.push_back (i->Changed.connect(boost::bind(&Playlist::content_changed, this, _1, _2, _3)));
367                 _content_connections.push_back (i->NotChanged.connect(boost::bind(&Playlist::content_not_changed, this)));
368         }
369 }
370
371 DCPTime
372 Playlist::video_end () const
373 {
374         DCPTime end;
375         BOOST_FOREACH (shared_ptr<Content> i, _content) {
376                 if (i->video) {
377                         end = max (end, i->end ());
378                 }
379         }
380
381         return end;
382 }
383
384 DCPTime
385 Playlist::text_end () const
386 {
387         DCPTime end;
388         BOOST_FOREACH (shared_ptr<Content> i, _content) {
389                 if (!i->text.empty ()) {
390                         end = max (end, i->end ());
391                 }
392         }
393
394         return end;
395 }
396
397 FrameRateChange
398 Playlist::active_frame_rate_change (DCPTime t, int dcp_video_frame_rate) const
399 {
400         for (ContentList::const_reverse_iterator i = _content.rbegin(); i != _content.rend(); ++i) {
401                 if (!(*i)->video) {
402                         continue;
403                 }
404
405                 if ((*i)->position() <= t) {
406                         /* This is the first piece of content (going backwards...) that starts before t,
407                            so it's the active one.
408                         */
409                         if ((*i)->video_frame_rate ()) {
410                                 /* This content specified a rate, so use it */
411                                 return FrameRateChange ((*i)->video_frame_rate().get(), dcp_video_frame_rate);
412                         } else {
413                                 /* No specified rate so just use the DCP one */
414                                 return FrameRateChange (dcp_video_frame_rate, dcp_video_frame_rate);
415                         }
416                 }
417         }
418
419         return FrameRateChange (dcp_video_frame_rate, dcp_video_frame_rate);
420 }
421
422 void
423 Playlist::set_sequence (bool s)
424 {
425         _sequence = s;
426 }
427
428 bool
429 ContentSorter::operator() (shared_ptr<Content> a, shared_ptr<Content> b)
430 {
431         if (a->position() != b->position()) {
432                 return a->position() < b->position();
433         }
434
435         /* Put video before audio if they start at the same time */
436         if (a->video && !b->video) {
437                 return true;
438         } else if (!a->video && b->video) {
439                 return false;
440         }
441
442         /* Last resort */
443         return a->digest() < b->digest();
444 }
445
446 /** @return content in ascending order of position */
447 ContentList
448 Playlist::content () const
449 {
450         return _content;
451 }
452
453 void
454 Playlist::repeat (ContentList c, int n)
455 {
456         pair<DCPTime, DCPTime> range (DCPTime::max (), DCPTime ());
457         BOOST_FOREACH (shared_ptr<Content> i, c) {
458                 range.first = min (range.first, i->position ());
459                 range.second = max (range.second, i->position ());
460                 range.first = min (range.first, i->end ());
461                 range.second = max (range.second, i->end ());
462         }
463
464         DCPTime pos = range.second;
465         for (int i = 0; i < n; ++i) {
466                 BOOST_FOREACH (shared_ptr<Content> j, c) {
467                         shared_ptr<Content> copy = j->clone ();
468                         copy->set_position (pos + copy->position() - range.first);
469                         _content.push_back (copy);
470                 }
471                 pos += range.second - range.first;
472         }
473
474         sort (_content.begin(), _content.end(), ContentSorter ());
475
476         reconnect ();
477         Changed ();
478 }
479
480 void
481 Playlist::move_earlier (shared_ptr<Content> c)
482 {
483         ContentList::iterator previous = _content.end ();
484         ContentList::iterator i = _content.begin();
485         while (i != _content.end() && *i != c) {
486                 previous = i;
487                 ++i;
488         }
489
490         DCPOMATIC_ASSERT (i != _content.end ());
491         if (previous == _content.end ()) {
492                 return;
493         }
494
495         shared_ptr<Content> previous_c = *previous;
496
497         DCPTime const p = previous_c->position ();
498         previous_c->set_position (p + c->length_after_trim ());
499         c->set_position (p);
500 }
501
502 void
503 Playlist::move_later (shared_ptr<Content> c)
504 {
505         ContentList::iterator i = _content.begin();
506         while (i != _content.end() && *i != c) {
507                 ++i;
508         }
509
510         DCPOMATIC_ASSERT (i != _content.end ());
511
512         ContentList::iterator next = i;
513         ++next;
514
515         if (next == _content.end ()) {
516                 return;
517         }
518
519         shared_ptr<Content> next_c = *next;
520
521         next_c->set_position (c->position ());
522         c->set_position (c->position() + next_c->length_after_trim ());
523 }
524
525 int64_t
526 Playlist::required_disk_space (int j2k_bandwidth, int audio_channels, int audio_frame_rate) const
527 {
528         int64_t video = uint64_t (j2k_bandwidth / 8) * length().seconds ();
529         int64_t audio = uint64_t (audio_channels * audio_frame_rate * 3) * length().seconds ();
530
531         BOOST_FOREACH (shared_ptr<Content> i, _content) {
532                 shared_ptr<DCPContent> d = dynamic_pointer_cast<DCPContent> (i);
533                 if (d) {
534                         if (d->reference_video()) {
535                                 video -= uint64_t (j2k_bandwidth / 8) * d->length_after_trim().seconds();
536                         }
537                         if (d->reference_audio()) {
538                                 audio -= uint64_t (audio_channels * audio_frame_rate * 3) * d->length_after_trim().seconds();
539                         }
540                 }
541         }
542
543         /* Add on 64k for bits and pieces (metadata, subs etc) */
544         return video + audio + 65536;
545 }
546
547 string
548 Playlist::content_summary (DCPTimePeriod period) const
549 {
550         string best_summary;
551         int best_score = -1;
552         BOOST_FOREACH (shared_ptr<Content> i, _content) {
553                 int score = 0;
554                 optional<DCPTimePeriod> const o = DCPTimePeriod(i->position(), i->end()).overlap (period);
555                 if (o) {
556                         score += 100 * o.get().duration().get() / period.duration().get();
557                 }
558
559                 if (i->video) {
560                         score += 100;
561                 }
562
563                 if (score > best_score) {
564                         best_summary = i->path(0).leaf().string();
565                         best_score = score;
566                 }
567         }
568
569         return best_summary;
570 }
571
572 pair<double, double>
573 Playlist::speed_up_range (int dcp_video_frame_rate) const
574 {
575         pair<double, double> range (DBL_MAX, -DBL_MAX);
576
577         BOOST_FOREACH (shared_ptr<Content> i, _content) {
578                 if (!i->video) {
579                         continue;
580                 }
581                 if (i->video_frame_rate()) {
582                         FrameRateChange const frc (i->video_frame_rate().get(), dcp_video_frame_rate);
583                         range.first = min (range.first, frc.speed_up);
584                         range.second = max (range.second, frc.speed_up);
585                 } else {
586                         FrameRateChange const frc (dcp_video_frame_rate, dcp_video_frame_rate);
587                         range.first = min (range.first, frc.speed_up);
588                         range.second = max (range.second, frc.speed_up);
589                 }
590         }
591
592         return range;
593 }