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