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